package vn.cuhanh.models;

import vn.cuhanh.R;
import vn.cuhanh.sys.DBAdapter;
import vn.cuhanh.utils.HelperFunc;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;

public class Model_Award {

	public static String getScoreFromDatabase(Context ctx, int codeId, String userName) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.gameCodeTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			cursor = dbAdapter.fetch("userName = '" + userName + "' AND codeId = " + String.valueOf(codeId));
			return getScoreFromDatabase(cursor);
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return null;
	}

	private static String getScoreFromDatabase(Cursor cursor) {
		cursor.moveToFirst();
		if (cursor.getCount() < 1 || cursor.isAfterLast()) {
			return null;
		}

		return cursor.getString(cursor.getColumnIndexOrThrow("codeValue"));
	}

	public static long insert(Context ctx, String userName, int codeId, String codeValue) {
		DBAdapter dbAdapter;
		Cursor cursor = null;
		dbAdapter = new DBAdapter(ctx, ctx.getResources().getString(
				R.string.gameCodeTable));
		try {
			if (dbAdapter.isClosed()) {
				dbAdapter.open();
			}
			ContentValues values = new ContentValues();
			values.put("userName", userName);
			values.put("codeId", codeId);
			values.put("codeValue", codeValue);
			return dbAdapter.insert(values);
		} catch (SQLException e) {
			HelperFunc.readStackTrace(e);
		} finally {
			try {
				if (cursor != null) {
					cursor.close();
				}
				dbAdapter.close();
			} catch (Exception e) {
				HelperFunc.readStackTrace(e);
			}
		}
		return 0;
	}
}
